package com.sanbi.erp.core.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Desc:上传文件到文件服务器
 * @Data: 2022/11/02
 * @Author: xyp
 */
@Slf4j
public class OkHttpUtil {

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .readTimeout(2, TimeUnit.MINUTES)
            .build();

    /**
     * get
     *
     * @param url   请求的url
     * @param param 请求的参数
     * @return
     */
    public static String get(String url, Map<String, String> param) throws IOException {
        StringBuilder sb = new StringBuilder(url);
        if (param != null && param.keySet().size() > 0) {
            boolean firstFlag = true;
            for (Map.Entry<String, String> entry : param.entrySet()) {
                if (firstFlag) {
                    sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        Request request = new Request.Builder().url(sb.toString()).build();
        Response response = okHttpClient.newCall(request).execute();
        int status = response.code();
        if (response.isSuccessful()) {
            return response.body().string();
        }
        return String.valueOf(status);
    }

    /**
     * get
     *
     * @param url   请求的url
     * @param param 请求的参数
     * @return
     */
    public static String getForHeader(String url, Map<String, String> param) throws IOException {
        StringBuffer sb = new StringBuffer(url);
        if (param != null && param.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = param.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request.Builder()
                .addHeader("key", "value")
                .url(sb.toString())
                .build();
        Response response = null;

        response = okHttpClient.newCall(request).execute();
        int status = response.code();
        if (response.isSuccessful()) {
            return response.body().string();
        }
        return String.valueOf(status);
    }

    /**
     * Post请求发送JSON数据
     *
     * @param url        请求Url
     * @param jsonParams 请求的JSON
     */
    public static String postJsonParams(String url, String jsonParams) {
//        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response = null;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .build();
        try {
            response = client.newCall(request).execute();
            int status = response.code();
            log.info("状态码:" + status);
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        }
        return String.valueOf(response.code());

    }

    /**
     * Post请求发送x-www-form-urlencoded格式数据
     *
     * @param url        请求Url
     * @param jsonParams 请求的JSON
     */
    public static String postJsonParams2(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            log.info("状态码:" + status);
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        }
        return String.valueOf(response.code());

    }

    /**
     * Post请求发送xml类型数据
     *
     * @param url 请求Url
     * @param xml 请求的xml
     */
    public static String postXmlParams(String url, String xml) {
        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * 上传二维码图片/文件上传
     *
     * @param url      接口地址（接口方法路劲）
     *                 列：http://192.168.1.117:8070/file/upload
     * @param fileName 本地图片存储完整路径
     *                 列：C:\Users\23026\Desktop\tempQrcode\1663317563520.png
     * @param name     文件名称带后缀
     *                 列：1663317563520.png
     * @return
     */
    public static String postPNG(String url, String fileName, String name) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/png"), new File(fileName));
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", name, requestBody)
                .build();
        Request request = new Request.Builder()
                .header("Content-Type", "mutipart/from-data")
                .post(body)
                .url(url)
                .build();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .build();
        int code = 0;
        try {
            Response response = client.newCall(request).execute();
            code = response.code();
            if (response.isSuccessful()) {
                String resp = response.body().string();
                return resp;
            }
        } catch (IOException e) {
            log.error("调用上传服务失败", e);
        }
        log.info("{}调用上传服务失败",code);
        return "调用上传服务失败";
    }


}
